<template>
  <div class="container-box">
    <common-crud ref="crudRef" @search="handleSearch">
      <template #table-header>
        <el-button v-permission="'system:user:add'" type="primary" @click="handleAdd">
          新增
        </el-button>
      </template>
      <template #search-form="{ searchForm }">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
      </template>
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="nickName" label="昵称" />
      <el-table-column prop="introduction" label="介绍" />
      <el-table-column prop="role" label="角色" />
      <el-table-column prop="avatar" label="头像">
        <template #default="{ row }">
          <el-image style="width: 50px; height: 50px" :src="row.avatar" />
        </template>
      </el-table-column>

      <el-table-column prop="state" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.state ? 'success' : 'danger'" effect="plain">
            {{ row.state ? "正常" : "冻结" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间">
        <template #default="{ row }">
          {{ formatTime(row.createdAt) }}
          <el-tooltip effect="dark" placement="top">
            <template #content>{{ relativeTime(row.createdAt) }}</template>
            <el-icon class="time-icon">
              <Timer />
            </el-icon>
          </el-tooltip>
        </template>
      </el-table-column>
      <!-- 追加自定义操作按钮 -->
      <template #operation="{ row }">
        <el-button v-permission="'system:user:edit'" link type="primary" @click="handleEdit(row)">
          编辑
        </el-button>
        <el-button v-permission="'system:user:per'" link type="primary" @click="handleAssignRoles(row)">
          分配角色
        </el-button>
        <el-button v-permission="'system:user:paswd'" link type="primary" @click="restPassword(row)">
          重置密码
        </el-button>
      </template>
    </common-crud>
    <!-- 新增/编辑弹窗 -->
    <CommonDialog v-model="editDialogVisible" :title="title" width="500px" @close="handleDialogClose"
      @confirm="submitAssignUser" @cancel="handleDialogClose">
      <el-form ref="formRef" :rules="rules" label-width="100px" :model="formData">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="formData.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input v-model="formData.introduction" placeholder="请输入介绍" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <avatar-upload v-model="formData.avatar" @change="handleAvatarChange" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="formData.state">
            <el-radio label="true">正常</el-radio>
            <el-radio label="false">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <div>默认密码为123456</div> -->
      </el-form>
    </CommonDialog>
    <!-- 角色分配对话框 -->
    <CommonDialog v-model="roleDialogVisible" title="分配角色" width="500px" @close="handleRoleDialogClose"
      @confirm="submitAssignRoles" @cancel="handleRoleDialogClose">
      <el-form :model="roleForm" :rules="rulesRole" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="roleForm.roleId" placeholder="请选择角色" style="width: 100%">
            <el-option v-for="role in roleOptions" :key="role.id" :label="role.cnName" :value="role.id" />
          </el-select>
        </el-form-item>
      </el-form>
    </CommonDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { Timer } from "@element-plus/icons-vue"
import CommonCrud from "@/components/CommonCrud/index.vue"
import { getUserList, updateUserRole, addUser, editUser } from "@/api/user"
import { getRoleList } from "@/api/role"
import { formatTime, relativeTime } from "@/utils/format"
import type { UploadProps } from "element-plus"
import AvatarUpload from "@/components/Upload/index.vue"
import { rules, rulesRole } from "./rules.ts"

const imageUrl = ref("")
const crudRef = ref()
const editDialogVisible = ref(false)
const formData = ref({
  username: "",
  nickName: "",
  introduction: "",
  avatar: "",
  state: true,
})
const title = ref("")
const formRef = ref()
const roleFormRef = ref()
const handleAvatarChange = (url: string) => {
  formData.value.avatar = url
}
// 查询
const handleSearch = async (params: any) => {
  crudRef.value.loading = true
  try {
    const res: any = await getUserList(params)
    if (res.code === 200) {
      crudRef.value.tableData = res.data.data
      crudRef.value.total = res.data.total
    }
  } finally {
    crudRef.value.loading = false
  }
}

// 提交
const submitAssignUser = async () => {
  if (title.value === "新增") {
    const res = await addUser({ ...formData.value, password: 123456 })
    if (res.code === 200) {
      ElMessage.success("添加成功")
      crudRef.value.handleSearch()
      handleDialogClose()
    }
  } else if (title.value === "编辑") {
    const res = await editUser(formData.value.id, formData.value)
    if (res.code === 200) {
      ElMessage.success("保存成功")
      crudRef.value.handleSearch()
      handleDialogClose()

    }
  }
}
const handleAdd = async () => {
  title.value = "新增"
  editDialogVisible.value = true

}
//编辑
const handleEdit = (row: any) => {
  title.value = "编辑"
  imageUrl.value = row.avatar
  formData.value = { ...row }
  editDialogVisible.value = true
}
// 删除
const handleDelete = async (row: any) => {
  const res: any = await deleteUser(row.id)
  if (res.code === 200) {
    ElMessage.success("删除成功")
    crudRef.value.handleSearch()
  }
}
// 角色相关
const roleDialogVisible = ref(false)
const roleOptions = ref([])
const roleForm = reactive({
  userId: "",
  roleId: "",
})
// 获取角色列表
const getRoles = async () => {
  const res: any = await getRoleList({ pageSize: 999 })
  if (res.code === 200) {
    roleOptions.value = res.data.data
  }
}

// 打开角色分配对话框
const handleAssignRoles = (row: any) => {
  roleForm.userId = row.id
  roleForm.roleId = roleOptions.value
    .filter((item) => row.role.includes(item.name))
    .map((item) => item.id)
    .join(",")
  roleDialogVisible.value = true
}

// 提交角色分配
const submitAssignRoles = async () => {
  const res: any = await updateUserRole(roleForm.userId, roleForm.roleId)
  if (res.code === 200) {
    ElMessage.success("分配成功")
    crudRef.value.handleSearch()
    handleRoleDialogClose()
  }
}
const handleDialogClose = () => {
  formRef.value.resetFields()
  formData.value = {
    username: "",
    nickName: "",
    introduction: "",
    avatar: "",
    state: true,
  }
  editDialogVisible.value = false
}
// 关闭角色分配对话框
const handleRoleDialogClose = () => {
  roleFormRef.value.resetFields()

  roleDialogVisible.value = false
}
const restPassword = (row: any) => {
  row.password = 123456

  ElMessageBox.confirm("确定要重置密码吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const { code } = await editUser(row.id, row)
      if (code == 200) {
        ElMessage.warning("重置成功！重置密码后，该用户对应的登录校验将失效，请及时通知用户")
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      })
    })

}
onMounted(() => {
  getRoles()
  handleSearch({})
})
</script>

<style lang="scss" scoped>
.el-tag {
  margin-right: 8px;
}

.time-icon {
  margin-left: 4px;
  cursor: pointer;
  color: var(--el-text-color-secondary);

  &:hover {
    color: var(--el-color-primary);
  }
}
</style>
